package com.example.adapter_sdk.quick;

import android.os.Build;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import com.example.adapter_sdk.R;
import com.example.imgload_sdk.ImgLoad;

public class BaseViewHolder extends RecyclerView.ViewHolder {

    //键值对类型  键为int类型  底层使用int以及object实现
    private SparseArray<View> sparseArray = new SparseArray<>();

    public BaseViewHolder(@NonNull View itemView) {
        super(itemView);
    }

    //查找控件方法  查找itemview下的子控件
    //泛型方法  返回值为一个View子类
    private <V extends View> V find(int id) {
        return itemView.findViewById(id);
    }

    public <V extends View> V getView(int id) {
        V v = (V) sparseArray.get(id);
        if (v != null) {
            return v;
        }
        v = find(id);
        if (v != null) {
            sparseArray.put(id, v);
        }
        return v;
    }

    public void setText(int id, String message) {
        if (TextUtils.isEmpty(message))
            return;
        TextView textView = getView(id);
        if (textView == null)
            return;
        textView.setText(message);
    }

    public void setVisibility(int id, boolean visibilityFlag) {
        View view = getView(id);
        if (view == null)
            return;
        view.setVisibility(visibilityFlag ? View.VISIBLE : View.GONE);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void setImage(int id, String path){
        ImageView image = getView(id);
        if (image == null)
            return;
        if (TextUtils.isEmpty(path)){
            image.setImageDrawable(image.getContext().getDrawable(R.drawable.default_loading));
            return;
        }
        ImgLoad.loadMatchImg(path,image);
    }

    public void setCirImage(int id,String path){
        if (TextUtils.isEmpty(path))
            return;
        ImageView image = getView(id);
        if (image == null)
            return;
        ImgLoad.loadCirImg(path,image);
    }
}
